package com.mobile.challenge.ui;

import android.os.Build;
import android.os.Bundle;
import android.security.keystore.KeyProperties;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.MutableLiveData;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.king.base.util.SharedPreferencesUtils;
import com.mobile.challenge.R;
import com.mobile.challenge.bean.DataBean;
import com.mobile.challenge.databinding.ActivityDashboardBinding;
import com.mobile.challenge.fingerprint.CommonTipDialog;
import com.mobile.challenge.fingerprint.FingerprintHelper;
import com.mobile.challenge.fingerprint.FingerprintUtil;
import com.mobile.challenge.fingerprint.FingerprintVerifyDialog;
import com.mobile.challenge.user.UserHelper;
import com.mobile.frame.mvvmframe.base.BaseActivity;

import static com.mobile.challenge.util.ConstantsKt.HAS_SHOWN_ENROLL_HINT;
import static com.mobile.challenge.util.ConstantsKt.IS_TOUCH_ID_ENROLLED;
import static com.mobile.challenge.util.ConstantsKt.LOCAL_FINGERPRINT_INFO;

public class DashboardActivity extends BaseActivity<DashboardViewModel, ActivityDashboardBinding> {

    private ImageView iv_fingerprint_login_switch;
    private TextView tv_nonsupport;
    private CommonTipDialog openFingerprintLoginTipDialog;
    private FingerprintHelper helper;
    private FingerprintVerifyDialog fingerprintVerifyDialog;
    private CommonTipDialog fingerprintVerifyErrorTipDialog;
    private CommonTipDialog closeFingerprintTipDialog;
    private boolean isOpen;
    private boolean isTouchIDEnrolled;
    private DataBean dataBean;
    public MutableLiveData<Boolean> enrollResult = new MutableLiveData<>();
    public LinearLayout container;

    @Override
    public int getLayoutId() {
        return R.layout.activity_dashboard;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        BottomNavigationView navView = findViewById(R.id.nav_view);
        container = mBinding.container;
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
        String loginDataJson = getIntent().getStringExtra("logindata");
        dataBean = new Gson().fromJson(loginDataJson, DataBean.class);

        isTouchIDEnrolled = SharedPreferencesUtils.getBoolean(this, IS_TOUCH_ID_ENROLLED);
        boolean hasShownHint = SharedPreferencesUtils.getBoolean(this, HAS_SHOWN_ENROLL_HINT, false);
        // 没有展示过，则提示用户开启
        if (!hasShownHint) {
            checkFingerprint();
        }
        UserHelper.Companion.getInstance().setUser(dataBean);
    }

    public DataBean getDataBean() {
        return dataBean;
    }

    private void checkFingerprint() {
        // 判断本地是否已经打开 没有的话 检查可用性
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isTouchIDEnrolled) {
            initialFingerprintHelper();
            if (helper.checkFingerprintAvailable(this) != -1) {
                //设备支持指纹登录
                mBinding.getRoot().post(() -> {
                    if (helper.checkFingerprintAvailable(DashboardActivity.this) != -1) {
                        showOpenFingerprintLoginDialog();
                    }
                });
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void initialFingerprintHelper() {
        helper = FingerprintHelper.getInstance();
        helper.init(getApplicationContext());
        helper.setCallback(new FingerprintHelper.SimpleAuthenticationCallback() {
            @Override
            public void onAuthenticationSucceeded(String value) {
                Log.e("hagan", "HomeActivity->onAuthenticationSucceeded-> value:" + value);
                SharedPreferencesUtils.put(DashboardActivity.this, IS_TOUCH_ID_ENROLLED, true);
                if (fingerprintVerifyDialog != null && fingerprintVerifyDialog.isShowing()) {
                    fingerprintVerifyDialog.dismiss();
                }
                isTouchIDEnrolled = true;
                Toast.makeText(DashboardActivity.this, "Fingerprint enabled", Toast.LENGTH_SHORT).show();
                saveLocalFingerprintInfo();
                enrollResult.setValue(true);
            }

            @Override
            public void onAuthenticationFail() {
                Log.e("hagan", "HomeActivity->onAuthenticationFail");
//                showFingerprintVerifyErrorInfo("指纹不匹配");
                // 使用系统提示
            }

            @Override
            public void onAuthenticationError(int errorCode, CharSequence errString) {
                Log.e("hagan", "HomeActivity->onAuthenticationError-> errorCode:" + errorCode + ",errString:" + errString);
                if (fingerprintVerifyDialog != null && fingerprintVerifyDialog.isShowing()) {
                    fingerprintVerifyDialog.dismiss();
                }
                Snackbar.make(container, errString, Snackbar.LENGTH_SHORT).show();
            }

            @Override
            public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                Log.e("hagan", "HomeActivity->onAuthenticationHelp-> helpCode:" + helpCode + ",helpString:" + helpString);
            }
        });
    }

    /**
     * 保存当前的指纹信息
     */
    @RequiresApi(Build.VERSION_CODES.M)
    private void saveLocalFingerprintInfo() {
        SharedPreferencesUtils.put(this, LOCAL_FINGERPRINT_INFO, FingerprintUtil.getFingerprintInfoString(getApplicationContext()));
    }

    private void showFingerprintVerifyErrorInfo(String info) {
        if (fingerprintVerifyDialog != null && fingerprintVerifyDialog.isShowing()) {
            fingerprintVerifyDialog.setContentText(info);
        }
    }

    private void showTipDialog(int errorCode, CharSequence errString) {
        if (fingerprintVerifyErrorTipDialog == null) {
            fingerprintVerifyErrorTipDialog = new CommonTipDialog(this);
        }
        fingerprintVerifyErrorTipDialog.setContentText("errorCode:" + errorCode + "," + errString);
        fingerprintVerifyErrorTipDialog.setSingleButton(true);
        fingerprintVerifyErrorTipDialog.setOnSingleConfirmButtonClickListener(new CommonTipDialog.OnDialogSingleConfirmButtonClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onConfirmClick(View v) {
                helper.stopAuthenticate();
            }
        });
        fingerprintVerifyErrorTipDialog.show();
    }

    private void showOpenFingerprintLoginDialog() {
        if (openFingerprintLoginTipDialog == null) {
            openFingerprintLoginTipDialog = new CommonTipDialog(this);
        }
        openFingerprintLoginTipDialog.setSingleButton(false);
        openFingerprintLoginTipDialog.setContentText("Would you like enable easy login with fingerprint?");
        openFingerprintLoginTipDialog.setOnDialogButtonsClickListener(new CommonTipDialog.OnDialogButtonsClickListener() {
            @Override
            public void onCancelClick(View v) {
//                Toast.makeText(DashboardActivity.this, "后续您可以在设置中开启", Toast.LENGTH_SHORT).show();
                Snackbar.make(container, "Can enable in MINE page later", Snackbar.LENGTH_SHORT).show();
            }

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onConfirmClick(View v) {
                openFingerprintLogin();
            }
        });
        openFingerprintLoginTipDialog.show();
        // 已经提示过用户 进行指纹登录
        SharedPreferencesUtils.put(this, HAS_SHOWN_ENROLL_HINT, true);
    }

    /**
     * @description 开启指纹登录功能
     * @author HaganWu
     * @date 2019/1/29-10:20
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void openFingerprintLogin() {
        Log.e("hagan", "openFingerprintLogin");

        helper.generateKey();
//        if (fingerprintVerifyDialog == null) {
//            fingerprintVerifyDialog = new FingerprintVerifyDialog(this);
//        }
//        fingerprintVerifyDialog.setContentText("请验证指纹");
//        fingerprintVerifyDialog.setOnCancelButtonClickListener(new FingerprintVerifyDialog.OnDialogCancelButtonClickListener() {
//            @Override
//            public void onCancelClick(View v) {
//                helper.stopAuthenticate();
//            }
//        });
//        fingerprintVerifyDialog.show();
        helper.setPurpose(KeyProperties.PURPOSE_ENCRYPT);
        helper.authenticate();
    }

    public boolean isTouchIDEnrolled() {
        return isTouchIDEnrolled;
    }
}